package com.lizardmind.haofudoctor.ui.diagnosis.sickMan.MedicalHistory

import android.databinding.ViewDataBinding
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.linxiao.framework.fragment.BaseFragment
import com.linxiao.framework.util.getDataBinding
import com.linxiao.framework.util.ke
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.databinding.FragmentMedicalHistoryBinding
import com.lizardmind.haofudoctor.manager.postApi
import com.lizardmind.haofudoctor.manager.setImageUrl
import com.lizardmind.haofudoctor.other.*
import com.lizardmind.haofudoctor.other.DoctorInfo
import com.lizardmind.haofudoctor.other.MedicalHistoryBean
import com.lizardmind.haofudoctor.other.Request
import com.lizardmind.haofudoctor.other.RongCloudUserBean
import com.lizardmind.haofudoctor.ui.diagnosis.diagnose.LookDiagnoseActivity
import com.lizardmind.haofudoctor.ui.diagnosis.visit.LookVisitActivity
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.fragment_medical_history.*
import kotlinx.android.synthetic.main.head_medical_history.*
import kotlinx.android.synthetic.main.head_medical_history.view.*
import kotlinx.android.synthetic.main.item_fang_an.view.*
import kotlinx.android.synthetic.main.popview_filtrate.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.act
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.toast

/**
 * Created by Administrator on 2017/10/23.
 * 患者——病历fragment
 */
class MedicalHistoryFragment : BaseFragment() {
    private val rUid by lazy{ act.intent.data.getQueryParameter("targetId") }

    private val list= arrayListOf<MedicalHistoryBean>()
    private val listTemp= arrayListOf<MedicalHistoryBean>()//用于筛选使用的临时list

    private val mAdapter by lazy { MedicalHistoryAdapter(list,context) }
    private lateinit var headView: View
    private lateinit var popView: View
    private lateinit var popWin: PopupWindow

    val binding by lazy { getDataBinding<FragmentMedicalHistoryBinding>(R.layout.fragment_medical_history) }
    override fun onCreatRootView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        headView=LayoutInflater.from(context).inflate(R.layout.head_medical_history,container,false)
        return binding.root
    }

    override fun onInitView(savedInstanceState: Bundle?) {
        popView=LayoutInflater.from(context).inflate(R.layout.popview_filtrate,null)

        mAdapter.setMyHeadView(headView)
        rvMedicalHistory.apply {
            layoutManager=LinearLayoutManager(context)
            adapter=mAdapter
        }

        getSickManData()
        getDoctorNote()
        refreshLayout.startRefresh()
        refreshLayout.setEnableLoadmore(false)
        refreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                super.onRefresh(refreshLayout)
                list.clear()
                getMedicalHistory()
            }
        })
        mAdapter.setOnBind(object: MedicalHistoryAdapter.OnBind{
            override fun onBind(itemBinding: ViewDataBinding, position: Int,bean:MedicalHistoryBean) {
                itemBinding.root.tvSeeMore.setOnClickListener {
                    when(bean.itemFlag){
                        1->startActivity<LookDiagnoseActivity>("id" to bean.id)
                        3->startActivity<FangAnActivity>("id" to bean.id)
                        2->startActivity<LookVisitActivity>("id" to bean.id)
                    }
                }
            }
        })

        headView.tvFiltrate.onClick { showFiltratePopWin() }
        headView.tvSupplement.onClick { toast("没有设计图") }

        popView.tvFiltrateWenZhenDan.onClick { filtrateMedicalHistory(1) }
        popView.tvFiltrateSuiFang.onClick { filtrateMedicalHistory(2) }
        popView.tvFiltrateFangAn.onClick { filtrateMedicalHistory(3) }
        popView.tvFiltrateAll.onClick {
            list.clear()
            list.addAll(listTemp)
            mAdapter.notifyDataSetChanged()
            popWin.dismiss()
        }

    }

    /**
     * 显示筛选popwindow
     */
    private fun showFiltratePopWin(){
        popWin=PopupWindow(popView,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true)
        popWin.setBackgroundDrawable(ColorDrawable(0x00000000))
        popWin.showAsDropDown(tvFiltrate,-tvFiltrate.width+50,10)
    }

    /**
     * 筛选病历
     */
    private fun filtrateMedicalHistory(flag:Int){
        list.clear()
        (0 until listTemp.size)
                .filter { listTemp[it].itemFlag==flag }
                .mapTo(list) { listTemp[it] }

        mAdapter.notifyDataSetChanged()
        popWin.dismiss()
    }

    /**
     * 获取病历数据
     */
    private fun getMedicalHistory(){
        observable{
            postApi<Request<List<MedicalHistoryBean>>>(hashMapOf(
                    "action" to "medical_records",
                    "token" to DoctorInfo.token,
                    "uid" to rUid.substring(1)
            ), Consumer {
                it.dispose {
                    list.addAll(it)
                    listTemp.addAll(it)
                    mAdapter.notifyDataSetChanged()
                }
            }, Action {
                refreshLayout.finishRefreshing()
            })
        }
    }

//    //获取该聊天用户的信息
//    private fun getSickManData(){
//        observable{
//            postApi<Request<UserBean>>(hashMapOf(
//                    "action" to "get_user_info",
//                    "id" to rUid
//            ), Consumer {
//                it.dispose {
//                    headView.imgIcon.setImageUrl(it.head_img)
//                    headView.tvName2.text=it.name
//                    headView.tvPhoneNum.text= if (it.phone=="") "暂无" else it.phone
//                }
//            }, Action {
//
//            })
//        }
//    }

    //获取该医生给该用户添加的备注
    private fun getDoctorNote() {
        observable {
            postApi<Request<BeiZhuBean>>(hashMapOf(
                    "action" to "doctor_note",
                    "token" to DoctorInfo.token,
                    "uid" to rUid.substring(1)
            ), Consumer {
                it.dispose {
                    headView.tvName1.text = it.name
                }
            })
        }
    }
    /**
     * 获取患者用户数据
     */
    private fun getSickManData() {
        observable {

            postApi<Request<RongCloudUserBean>>(hashMapOf("action" to "get_type",
                    "token" to DoctorInfo.token,
                    "id" to rUid.substring(1),
                    "type" to rUid[0].toString()),
                    Consumer {
                        it.dispose {
                            headView.imgIcon.setImageUrl(it.head_img)
                            headView.tvName2.text = it.name
                            headView.tvPhoneNum.text = "未填写"
                        }
                    })
        }
    }

}
